package com.rpcLearning.client.impl;

import com.rpcLearning.client.TransportSelector;
import com.rpcLearning.common.ReflectUtils;
import com.rpcLearning.proto.Peer;
import com.rpcLearning.transport.TransportClient;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author:zyh
 * @Time:2021-03-17-21:04
 * @email:1269231889@qq.com
 */
@Slf4j
public class RandomSelector implements TransportSelector {
    private List<TransportClient> clients;

    public RandomSelector() {
        clients = new CopyOnWriteArrayList<>();
    }

    @Override
    public synchronized void init(List<Peer> peers,
                     int count,
                     Class<? extends TransportClient> clazz) {
        count = Math.max(count,1);
        for (Peer peer : peers) {
            //一个端点可以连接count个client
            for (int i = 0; i < count; i++) {
                TransportClient transportClient = ReflectUtils.newInstance(clazz);
                transportClient.connect(peer);
                clients.add(transportClient);
            }
            log.info("connect server:{}", peer);
        }
    }

    @Override
    public TransportClient select() {
        int i = new Random()
                .nextInt(clients.size());
        return clients.get(i);
    }

    @Override
    public void release(TransportClient client) {
        clients.add(client);
    }

    @Override
    public void close() {
        for (TransportClient client : clients) {
            client.close();
        }
        clients.clear();
    }
}
